package com.central.kerberosManage.common;

import com.central.kerberosManage.common.utils.PropertyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author Tindy
 * @date 2022/5/5
 * @describe
 */
@Slf4j
public class CommonUtils {
    private static final Base64 BASE64 = new Base64();
    /**
     * encode password
     */
    public static String encodePassword(String password) {
        if (StringUtils.isEmpty(password)) {
            return StringUtils.EMPTY;
        }
        //if encryption is not turned on, return directly
        boolean encryptionEnable = PropertyUtils.getBoolean(Constants.HOST_PASSWD_ENCRYPTION_ENABLE, false);
        if (!encryptionEnable) {
            return password;
        }

        // Using Base64 + salt to process password
        String salt = PropertyUtils.getString(Constants.HOST_PASSWD_ENCRYPTION_SALT, Constants.HOST_PASSWD_ENCRYPTION_SALT_DEFAULT);
        String passwordWithSalt = salt + new String(BASE64.encode(password.getBytes(StandardCharsets.UTF_8)));
        return new String(BASE64.encode(passwordWithSalt.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * decode password
     */
    public static String decodePassword(String password) {
        if (StringUtils.isEmpty(password)) {
            return StringUtils.EMPTY;
        }

        //if encryption is not turned on, return directly
        boolean encryptionEnable = PropertyUtils.getBoolean(Constants.HOST_PASSWD_ENCRYPTION_ENABLE, false);
        if (!encryptionEnable) {
            return password;
        }

        // Using Base64 + salt to process password
        String salt = PropertyUtils.getString(Constants.HOST_PASSWD_ENCRYPTION_SALT, Constants.HOST_PASSWD_ENCRYPTION_SALT_DEFAULT);
        String passwordWithSalt = new String(BASE64.decode(password), StandardCharsets.UTF_8);
        if (!passwordWithSalt.startsWith(salt)) {
            log.warn("There is a password and salt mismatch: {} ", password);
            return password;
        }
        return new String(BASE64.decode(passwordWithSalt.substring(salt.length())), StandardCharsets.UTF_8);
    }
}
